<script setup lang="ts">
import type { AdjustInventoryParams, InventoryDetail } from '../types';

import { reactive, ref } from 'vue';

import { BasicForm, BasicModal, useForm, useVbenModal } from '@vben/uikit';

import { $t } from '#/locales';

import { useAdjustFormSchema } from '../data';
import { adjustInventory } from '../services';

const modalId = 'inventory-adjust-modal';
const [Modal, modalApi] = useVbenModal({
  title: $t('inventory.adjustModal.title'),
  fullscreenButton: false,
  showOkButton: true,
  showCancelButton: true,
  onConfirm: submitForm,
});



const loading = ref(false);
const formData = reactive<AdjustInventoryParams>({
  inventory_id: '',
  product_code: '',
  product_name: '',
  current_quantity: 0,
  adjust_type: 'adjust_in',
  adjust_quantity: 0,
  reason: '',
  remark: '',
});

// 表单配置
const [registerForm, { setProps, resetFields, validate }] = useForm({
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 19,
  },
  baseColProps: {
    span: 24,
  },
  schemas: useAdjustFormSchema(),
  model: formData,
});

// 重置表单
function resetForm(): void {
  Object.keys(formData).forEach((key) => {
    formData[key as keyof AdjustInventoryParams] =
      key === 'adjust_type' ? 'adjust_in' : '';
  });
  resetFields();
}

// 提交表单
async function submitForm(): Promise<void> {
  try {
    const valid = await validate();
    if (!valid) return;

    loading.value = true;
    const res = await adjustInventory(formData);
    if (res.code === 0) {
      modalApi.close();
      // 通知父组件刷新数据
      window.$message.success($t('inventory.adjustModal.success'));

      // 重置表单
      resetForm();

      // 触发自定义事件，通知父组件刷新数据
      const event = new CustomEvent('inventory-adjusted', {
        detail: { success: true },
      });
      window.dispatchEvent(event);
    } else {
      window.$message.error(res.message || $t('inventory.adjustModal.failed'));
    }
  } catch (error) {
    window.$message.error($t('inventory.adjustModal.failed'));
    console.error('Adjust inventory failed:', error);
  } finally {
    loading.value = false;
  }
}

// 打开模态框
function handleOpenModal(row: InventoryDetail): void {
  // 填充表单数据
  formData.inventory_id = row.inventory_id;
  formData.product_code = row.product_code || '';
  formData.product_name = row.product_name || '';
  formData.current_quantity = row.quantity || 0;
  formData.adjust_type = 'adjust_in';
  formData.adjust_quantity = 0;
  formData.reason = '';
  formData.remark = '';

  // 更新表单
  setProps({
    schemas: useAdjustFormSchema(),
  });

  // 打开模态框
  modalApi.open();
}

// 导出方法供父组件使用
defineExpose({
  openModal: handleOpenModal,
});
</script>
<template>
  <Modal>
    <BasicForm
      :model="formData"
      :schema="formSchema"
      :label-width="120"
      @values-change="handleValuesChange"
    />
  </Modal>
</template>
<style lang="less" scoped></style>
